package com.baffle.socket.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baffle.socket.model.Matching;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonUtils {
	
	private static Map<String, Object> jsonMap = new HashMap<String, Object>();

	private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);

	public static <T> T convertJsonStringToObj(String jsonString, Class<T> target) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(jsonString, target);
		} catch (IOException e) {
			LOGGER.error("Can't not convert json string to object {}", target.getSimpleName(), e);
			return null;
		}
	}

	public static String convertObjToJsonString(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			LOGGER.error("Can't not convert object to json string.", e);
			return "";
		}
	}

	public static String createJsonString(String key, Object value) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(key, value);
		return jsonObject.toString();
	}

	public static Map<String, Object> getResponseJson(String jsonStr, String fileUrl) {
		Map<String, Object> map = new HashMap<String, Object>();
		String allJsonStr = "";
		// 转换成为JSONObject对象
		if (jsonStr != null && jsonStr != "") {
			String orderNmber = jsonStr.substring(0, 4);
			map.put("orderNmber", orderNmber);
			map.put("outTime", "");
			map.put("allJsonStr", "");
			jsonStr = jsonStr.substring(jsonStr.indexOf("{"), jsonStr.length());
			JSONObject jsonObj = JSONObject.parseObject(jsonStr);
			JSONObject headJson = jsonObj.getJSONObject("HEAD");
			if (!headJson.isEmpty()) {
				String merchId = "";
				if (headJson.get("MERCH_ID") != null && headJson.get("MERCH_ID") != "") {
					merchId = headJson.get("MERCH_ID").toString();
				}

				String tranDatetime = "";
				if (headJson.get("TRAN_DATETIME") != null && headJson.get("TRAN_DATETIME") != "") {
					tranDatetime = headJson.get("TRAN_DATETIME").toString();
				}

				String orderIdJson = "";
				if (headJson.get("ORDER_ID") != null && headJson.get("ORDER_ID") != "") {
					orderIdJson = headJson.get("ORDER_ID").toString();
				}

				JSONObject allJson = new JSONObject();
				JSONObject contentHead = new JSONObject();
				contentHead.put("MERCH_ID", merchId);
				contentHead.put("TRAN_DATETIME", tranDatetime);
				contentHead.put("ORDER_ID", orderIdJson);
				allJson.put("HEAD", contentHead);

				JSONObject bodyJson = jsonObj.getJSONObject("BODY");
				JSONObject dataJson = bodyJson.getJSONObject("DATA");
				if (!dataJson.isEmpty()) {
					String tranCode = "";
					if (dataJson.get("TRAN_CODE") != null && dataJson.get("TRAN_CODE") != "") {
						tranCode = dataJson.get("TRAN_CODE").toString();
					}

					Matching matchingDto = new Matching();

					// 扣款报文
					if (tranCode.equals("310002")) {
						matchingDto = getDeductionJsonStr(dataJson);
					}
					// 查询报文
					if (tranCode.equals("310008")) {
						matchingDto = getSelectJsonStr(dataJson);
						String originalOrderId = matchingDto.getOriginalOrderId();
						String orderId = jsonMap.get("orderIdJson").toString();
						if(originalOrderId.equals(orderId)){
							map = jsonMap;
							map.put("orderNmber", orderNmber);
							return map;
						}
					}

					String payerCardNo = matchingDto.getPayerCardNo();
					String amount = matchingDto.getAmount();
					String payerCardNoAmount = payerCardNo + "|" + amount;

					JSONObject contentData = new JSONObject();
					contentData.put("TRAN_CODE", tranCode);
					contentData.put("ORIGINAL_TRAN_CODE", "310002");
					contentData.put("ORIGINAL_ORDER_ID", orderIdJson);

					contentData.put("CARD_NO", payerCardNo);
					contentData.put("CURRENCY", matchingDto.getCurrency());
					contentData.put("AMOUNT", amount);
					contentData.put("ORIGINAL_RSP_CODE", "00000000");
					contentData.put("ORIGINAL_RSP_DESC", "");
					contentData.put("FC_RSP_CODE", "");

					//查询对比文件值（1有数据,0没有[全部返回SUCCESS]）
					int isTrue = 0; 
					int outTime = 0;
					List<Matching> matchingList = FileUtils.readTxt(fileUrl);
					if (matchingList != null && matchingList.size() > 0) {
						for (Matching matching : matchingList) {
							String payerCardNoFile = matching.getPayerCardNo();
							String amountFile = matching.getAmount();
							String payerCardNoAmountFile = payerCardNoFile + "|" + amountFile;
							
							if (payerCardNoAmount.equals(payerCardNoAmountFile)) {
								contentData.put("RSP_CODE", matching.getRspCode());
								String stateCode = matching.getStateCode();
								if (stateCode.equals("SUCCESS")) {
									contentData.put("FC_RSP_DESC", "成功");
								}
								if (stateCode.equals("FAILED")) {
									contentData.put("FC_RSP_DESC", "失败");
								}
								if (stateCode.equals("UNKNOWN2")) {
									contentData.put("FC_RSP_DESC", "异常");
								}
								contentData.put("STATE_CODE", stateCode);
								outTime = matching.getOutTime();
								isTrue = 1;
								
								FileUtils.modifyFileContent(fileUrl, payerCardNoAmount); //修改读取状态
								break;
							}
						}
					}
					
					if (isTrue == 0) {
						contentData.put("RSP_CODE", "00000000");
						contentData.put("STATE_CODE", "SUCCESS");
						contentData.put("FC_RSP_DESC", "成功");
					}
					
					JSONObject dataObject = new JSONObject();
					dataObject.put("DATA", contentData);
					allJson.put("BODY", dataObject);
					// json格式化
					allJsonStr = JSON.toJSONString(allJson, SerializerFeature.PrettyFormat,
							SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
					map.put("outTime", outTime);
					map.put("allJsonStr", allJsonStr);
					jsonMap = map;
					jsonMap.put("orderIdJson", orderIdJson);
				}
			}
		}

		return map;
	}

	/*
	 * 扣款报文
	 */
	public static Matching getDeductionJsonStr(JSONObject dataJson) {
		Matching matching = new Matching();
		String payerCardNo = "";
		if (dataJson.get("PAYER_CARD_NO") != null && dataJson.get("PAYER_CARD_NO") != "") {
			payerCardNo = dataJson.get("PAYER_CARD_NO").toString();
			matching.setPayerCardNo(payerCardNo);
		}

		String currency = "";
		if (dataJson.get("CURRENCY") != null && dataJson.get("CURRENCY") != "") {
			currency = dataJson.get("CURRENCY").toString();
			matching.setCurrency(currency);
		}

		String amount = "";
		if (dataJson.get("AMOUNT") != null && dataJson.get("AMOUNT") != "") {
			amount = dataJson.get("AMOUNT").toString();
			matching.setAmount(amount);
		}

		return matching;
	}

	/*
	 * 查询报文
	 */
	public static Matching getSelectJsonStr(JSONObject dataJson) {
		Matching matching = new Matching();
		String originalOrderId = "";
		if (dataJson.get("ORIGINAL_ORDER_ID") != null && dataJson.get("ORIGINAL_ORDER_ID") != "") {
			originalOrderId = dataJson.get("ORIGINAL_ORDER_ID").toString();
			matching.setOriginalOrderId(originalOrderId);
		}

		return matching;
	}

	public static String getResponseJsonStr(String jsonStr, String fileUrl) {
		String allJsonStr = "";
		// 转换成为JSONObject对象
		JSONObject jsonObj = JSONObject.parseObject(jsonStr);
		JSONObject headJson = jsonObj.getJSONObject("HEAD");
		if (!headJson.isEmpty()) {
			String merchId = "";
			if (headJson.get("MERCH_ID") != null && headJson.get("MERCH_ID") != "") {
				merchId = headJson.get("MERCH_ID").toString();
			}

			String tranDatetime = "";
			if (headJson.get("TRAN_DATETIME") != null && headJson.get("TRAN_DATETIME") != "") {
				tranDatetime = headJson.get("TRAN_DATETIME").toString();
			}

			String orderIdJson = "";
			if (headJson.get("ORDER_ID") != null && headJson.get("ORDER_ID") != "") {
				orderIdJson = headJson.get("ORDER_ID").toString();
			}

			List<Matching> matchingList = FileUtils.readTxt(fileUrl);
			JSONObject allJson = new JSONObject();
			if (matchingList != null && matchingList.size() > 0) {

				JSONObject contentHead = new JSONObject();
				contentHead.put("MERCH_ID", merchId);
				contentHead.put("TRAN_DATETIME", tranDatetime);
				contentHead.put("ORDER_ID", orderIdJson);
				allJson.put("HEAD", contentHead);

				JSONObject bodyJson = jsonObj.getJSONObject("BODY");
				JSONObject dataJson = bodyJson.getJSONObject("DATA");
				if (!dataJson.isEmpty()) {
					String tranCode = "";
					if (dataJson.get("TRAN_CODE") != null && dataJson.get("TRAN_CODE") != "") {
						tranCode = dataJson.get("TRAN_CODE").toString();
					}

					String payerCardNo = "";
					if (dataJson.get("PAYER_CARD_NO") != null && dataJson.get("PAYER_CARD_NO") != "") {
						payerCardNo = dataJson.get("PAYER_CARD_NO").toString();
					}

					String currency = "";
					if (dataJson.get("CURRENCY") != null && dataJson.get("CURRENCY") != "") {
						currency = dataJson.get("CURRENCY").toString();
					}

					String amount = "";
					if (dataJson.get("AMOUNT") != null && dataJson.get("AMOUNT") != "") {
						amount = dataJson.get("AMOUNT").toString();
					}

					String payerCardNoAmount = payerCardNo + "|" + amount;

					JSONObject contentData = new JSONObject();
					contentData.put("TRAN_CODE", tranCode);
					contentData.put("ORIGINAL_TRAN_CODE", "310002");
					contentData.put("ORIGINAL_ORDER_ID", orderIdJson);

					contentData.put("CARD_NO", payerCardNo);
					contentData.put("CURRENCY", currency);
					contentData.put("AMOUNT", amount);
					contentData.put("ORIGINAL_RSP_CODE", "00000000");
					contentData.put("ORIGINAL_RSP_DESC", "");
					contentData.put("FC_RSP_CODE", "");
					contentData.put("FC_RSP_DESC", "");

					for (Matching matching : matchingList) {
						String payerCardNoFile = matching.getPayerCardNo();
						String amountFile = matching.getAmount();
						String payerCardNoAmountFile = payerCardNoFile + "|" + amountFile;
						if (payerCardNoAmount.equals(payerCardNoAmountFile)) {

							contentData.put("RSP_CODE", matching.getRspCode());
							contentData.put("STATE_CODE", matching.getStateCode());
							JSONObject dataObject = new JSONObject();
							dataObject.put("DATA", contentData);
							allJson.put("BODY", dataObject);
							// json格式化
							allJsonStr = JSON.toJSONString(allJson, SerializerFeature.PrettyFormat,
									SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
						}
					}

				}

			}
		}
		return allJsonStr;
	}

}
